
package com.xifan.myaccount.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.TextView;

import com.xifan.myaccount.R;
import com.xifan.myaccount.adapter.TypeStatsAdapter;
import com.xifan.myaccount.database.DatabaseImpl;
import com.xifan.myaccount.entity.RecordDetail;
import com.xifan.myaccount.entity.TypeStats;
import com.xifan.myaccount.util.DataAnalyzer;
import com.xifan.myaccount.util.UiHelper;
import com.xifan.myaccount.util.Util;
import com.xifan.myaccount.widget.MoneyView;
import com.xifan.myaccount.widget.TasksCompletedView;

import java.util.ArrayList;
import java.util.List;

public class StatFragment extends Fragment {

    private TasksCompletedView mCircle;
    private TextView mStatType;
    private TextView mTopTypeName;
    private TextView mTips;
    private MoneyView mTopTypeMoney;
    private ListView mStatsList;

    private Context mContext;

    private int opType;

    private int mSelectedMonth = -1;
    private float curMoney = -1f;
    private float lastMoney = -1f;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        opType = getArguments().getInt("opType");
        mContext = getActivity();
        LoadInfoTask task = new LoadInfoTask();
        task.execute();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_statistics, null);
        mCircle = (TasksCompletedView) view.findViewById(R.id.stat_top_circle);
        mStatType = (TextView) view.findViewById(R.id.stat_top_section_title);
        mTopTypeName = (TextView) view.findViewById(R.id.stat_top_text_title);
        mTips = (TextView) view.findViewById(R.id.stats_top_tips_content);
        mTopTypeMoney = (MoneyView) view.findViewById(R.id.stat_top_text_detail);
        mStatsList = (ListView) view.findViewById(R.id.stat_type_list);

        return view;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_calendar_chooser:
                AlertDialog monthDialog = UiHelper.createMonthPickerDialog(mContext,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == Dialog.BUTTON_POSITIVE) {
                                    new LoadInfoTask().execute();
                                }
                            }
                        }, new OnValueChangeListener() {
                            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                                mSelectedMonth = newVal - 1;
                            }
                        }, mSelectedMonth, getString(R.string.month_dialog_title));
                monthDialog.show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private class LoadInfoTask extends AsyncTask<Void, Void, List<TypeStats>> {
        @SuppressWarnings("unchecked")
        protected List<TypeStats> doInBackground(Void... params) {
            int accountId = Util.getCurrentAccountId(mContext);
            String defaultDate;
            if (mSelectedMonth == -1) {
                mSelectedMonth = Util.getMonth();
            }
            defaultDate = Util.getDatetimeByMonth(mSelectedMonth);
            DatabaseImpl db = new DatabaseImpl(mContext, true);
            List<RecordDetail> list = new ArrayList<RecordDetail>();
            list = db.doQuery(DatabaseImpl.DB_TABLE_DETAIL, "where accountId=" + accountId
                    + " and strftime('%m',recordDate)=strftime('%m','" + defaultDate
                    + "') and recordOp=" + opType, true);

            if (list.size() > 0) {
                List<TypeStats> statsList = new ArrayList<TypeStats>();
                DataAnalyzer analyzer = new DataAnalyzer(list);
                statsList = analyzer.getAnalyzedTypes();
                curMoney = analyzer.getTotlMoney();

                // get last month data
                List<RecordDetail> lastList = new ArrayList<RecordDetail>();
                defaultDate = Util.getDatetimeByMonth(mSelectedMonth - 1);
                lastList = db.doQuery(DatabaseImpl.DB_TABLE_DETAIL, "where accountId=" + accountId
                        + " and strftime('%m',recordDate)=strftime('%m','" + defaultDate
                        + "') and recordOp=" + opType, true);
                if (lastList.size() > 0) {
                    lastMoney = 0; // set to 0
                    for (int i = 0, s = lastList.size(); i < s; i++) {
                        lastMoney += lastList.get(i).getRawMoney();
                    }
                }
                db.close();
                return statsList;
            } else {
                db.close();
                return new ArrayList<TypeStats>();
            }
        }

        protected void onPostExecute(List<TypeStats> result) {
            super.onPostExecute(result);
            mStatType
                    .setText(String
                            .format(opType == RecordDetail.TYPE_EXPEND ? getString(R.string.stats_expend_title)
                                    : getString(R.string.stats_revenue_title), mContext
                                    .getResources().getStringArray(R.array.months)[mSelectedMonth]));

            mStatsList.setAdapter(new TypeStatsAdapter(mContext, result, opType));
            UiHelper.setListViewHeightBasedOnChildren(mStatsList);
            if (result.size() > 0) {
                TypeStats type = result.get(0);
                RecordDetail tmpDetail = new RecordDetail();
                tmpDetail.setMoney(type.getTypeMoney());
                mCircle.setProgress(type.getPercentage());
                mTopTypeName.setText(type.getTypeName());
                mTopTypeMoney.setText(tmpDetail.getMoney());
                mTips.setText(getTipString(result.size()));
            } else {
                mCircle.setProgress(0);
                mTopTypeName.setText(getString(R.string.stats_top_title_no_data));
                mTopTypeMoney.setText("");
                mTips.setText(getString(R.string.stats_top_title_no_data));
            }
        }
    }

    private String getTipString(int recordTimes) {
        StringBuilder sb = new StringBuilder();
        sb.append("本月总共开销" + curMoney + "元\n");
        sb.append("使用麦本记账" + recordTimes + "次，");
        if (recordTimes < 15)
            sb.append("要加油坚持记账哦\n");
        else
            sb.append("你已经打败了95%的人，形成了记账的好习惯\n");

        if (curMoney < lastMoney && lastMoney != -1f)
            sb.append("恭喜！本月支出比上月支出少了").append(lastMoney - curMoney).append("元\n");
        else if (curMoney > lastMoney)
            sb.append("本月支出比上月多了").append(curMoney - lastMoney).append("元\n");
        else if (lastMoney == -1f) {
            sb.append("上月暂无记录，请持之以恒，使用麦本记账\n");
        }
        return sb.toString();
    }
}
